"""
RGB主题色控制器 - 核心版本
功能：读取Windows主题色并应用到RGB设备
"""

import winreg
import time
import threading
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor

class RGBThemeController:
    def __init__(self):
        self.client = None
        self.devices = []
        self.current_color = None
        self.running = True
        self.display_on = True

        print("正在启动RGB主题色控制器...")
        self.connect_openrgb()

    def connect_openrgb(self, max_retries=5):
        """连接到OpenRGB SDK服务器"""
        for attempt in range(max_retries):
            try:
                print(f"尝试连接OpenRGB (尝试 {attempt + 1}/{max_retries})...")
                self.client = OpenRGBClient(address='127.0.0.1', port=6742)
                self.devices = self.client.devices
                print(f"✓ 成功连接! 检测到 {len(self.devices)} 个设备:")
                for device in self.devices:
                    print(f"  - {device.name} ({len(device.leds)} LEDs)")
                return True
            except Exception as e:
                print(f"✗ 连接失败: {e}")
                if attempt < max_retries - 1:
                    print("5秒后重试...")
                    time.sleep(5)

        print("无法连接到OpenRGB。请确保:")
        print("1. OpenRGB正在运行")
        print("2. SDK服务器已启动（设置 → SDK服务器）")
        return False

    def get_windows_accent_color(self):
        """从Windows注册表读取主题强调色"""
        try:
            # 打开注册表键
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER,
                r"Software\Microsoft\Windows\DWM"
            )

            # 读取AccentColor值（DWORD格式：AABBGGRR）
            accent_color, _ = winreg.QueryValueEx(key, "AccentColor")
            winreg.CloseKey(key)

            # 解析颜色（AABBGGRR格式）
            r = accent_color & 0xFF
            g = (accent_color >> 8) & 0xFF
            b = (accent_color >> 16) & 0xFF

            return (r, g, b)

        except Exception as e:
            print(f"读取主题色失败: {e}")
            # 返回默认蓝色
            return (0, 120, 215)

    def apply_color(self, r, g, b):
        """应用颜色到所有RGB设备"""
        if not self.client or not self.devices:
            return

        try:
            color = RGBColor(r, g, b)
            for device in self.devices:
                device.set_color(color)
            self.current_color = (r, g, b)
            print(f"✓ 应用颜色: RGB({r}, {g}, {b})")
        except Exception as e:
            print(f"✗ 应用颜色失败: {e}")

    def turn_off_rgb(self):
        """关闭所有RGB（全黑）"""
        print("显示器关闭，关闭RGB...")
        self.apply_color(0, 0, 0)
        self.display_on = False

    def restore_theme_color(self):
        """恢复Windows主题色"""
        print("显示器唤醒，恢复主题色...")
        r, g, b = self.get_windows_accent_color()
        self.apply_color(r, g, b)
        self.display_on = True

    def monitor_theme_color(self):
        """监控主题色变化（每30秒检查一次）"""
        print("开始监控Windows主题色...")

        while self.running:
            if self.display_on:
                r, g, b = self.get_windows_accent_color()

                # 只在颜色变化时更新
                if self.current_color != (r, g, b):
                    print(f"检测到主题色变化: RGB({r}, {g}, {b})")
                    self.apply_color(r, g, b)

            # 每30秒检查一次
            time.sleep(30)

    def start(self):
        """启动控制器"""
        # 初始应用主题色
        r, g, b = self.get_windows_accent_color()
        print(f"当前Windows主题色: RGB({r}, {g}, {b})")
        self.apply_color(r, g, b)

        # 在后台线程监控主题色变化
        monitor_thread = threading.Thread(
            target=self.monitor_theme_color,
            daemon=True
        )
        monitor_thread.start()

        print("\n✓ RGB主题色控制器运行中...")
        print("主题色会自动同步到RGB设备")
        print("按 Ctrl+C 退出\n")

        # 主线程保持运行
        try:
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n正在退出...")
            self.running = False

    def stop(self):
        """停止控制器"""
        self.running = False

if __name__ == "__main__":
    controller = RGBThemeController()
    if controller.client:
        controller.start()
    else:
        print("启动失败，请检查OpenRGB连接")
        input("按Enter退出...")